<?php

namespace app\admin\controller;

use app\admin\model\FileOss;
use app\admin\model\PohtoInstitution;
use app\admin\model\PohtoList as PohtoListModel;
use app\admin\model\PohtoListImage as PohtoListImageModel;
use app\admin\model\PohtoListImageTwo;
use app\admin\service\OssService;
use app\BaseController;
use GuzzleHttp\Client;
use think\facade\Db;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;

class Index extends BaseController
{
    public function index()
    {
//        $sql = new PohtoListImageModel();
//        $imgList = $sql->limit(10)->order('image_path', 'asc')->select()->toArray();
//        dump($imgList);

//        $url = 'localhost:7001/image/tt'.signUrl('/1');
//        echo $url;
//        $oss = new OssService();
//        $prefix = "album/miaotangyinghua/二佐/VOL.042 二佐Nisa - 制服黑三本/";
//        $list = $oss->getFileList($prefix);
//        dump($list);
//        dump($list);
//        $url = $oss->signId(338);
//        echo $url;
//        'album/miaotangyinghua/erzuo/1/[喵糖映画] VOL.042 二佐Nisa - 制服黑三本-1.jpg'
//        $sql = new PohtoInstitution();
//        $list = $sql->select();
//        foreach ($list as $key => $value) {
//            $path = explode(config('oss.endpoint').'/', $value->cover);
//            $info = [
//                'userId' => 1,
//                'type' => 1,
//                'delPath' =>$path[1],
//                'fileSize' => 0,
//            ];
//            $fileSql = new FileOss();
//            $fileSql->save($info);
//            $value->cover_id = $fileSql->id;
//            $value->save();
//        }
    }

//    public function create()
//    {
//        $name = '\稚乖画册\fulito';
//        $path = 'E:\album'.$name;
//        $toPath = 'E:\album-zip'.$name;
//        //  读取$path目录下的所有文件夹
//        $dir = opendir($path);
//        while ($file = readdir($dir)) {
//            if ($file != '.' && $file != '..') {
//                $newPath = $path . '/' . $file;
//                $newToPath = $toPath . '/' . $file;
//                if (is_dir($newPath)) {
//                    if (!file_exists($newToPath)) {
//                        mkdir($newToPath, 0777, true);
//                    }
//                }
//            }
//        }
//        $this->yidong($path, $toPath);
//    }
//
//    public function yidong($path, $toPath)
//    {
//        $dir = opendir($path);
//        while ($file = readdir($dir)) {
//            if ($file != '.' && $file != '..') {
//                $childPath = $path . '/' . $file;
//                $toChildPath = $toPath . '/' . $file;
//                $dirTwo = opendir($childPath);
//                while ($fileChilder = readdir($dirTwo)) {
//                    if ($fileChilder != '.' && $fileChilder != '..') {
//                        //  匹配出所有.7z文件 移动到新文件夹
//                        $newPath = $childPath . '/' . $fileChilder;
//                        $newToPath = $toChildPath . '/' . $fileChilder;
//                        if (is_file($newPath)) {
//                            if(strpos($fileChilder, '.7z')) {
//                                rename($newPath, $newToPath);
//                            } else if(strpos($fileChilder, '.bat')) {
//                                unlink($newPath);
//                            }
//                        }
//                    }
//                }
//            }
//        }
//    }



    public function hello($name = 'ThinkPHP8')
    {
        return 'hello,' . $name;
    }

    public function savePathAll()
    {
        $sql = new PohtoListImageModel();
        $imgList = $sql->where('image_path', '=', null)->limit(1)->order('image_path', 'asc')->select()->toArray();
        if(count($imgList) > 0) {
            foreach ($imgList as $k => $v) {
                return $this->savePath($v['photo_id']);
            }
        }
    }

    public function savePath($id) {
//        $id = request()->get('id');
//        if(empty($id)) {
//            return result()->fail("请输入id", 500);
//        }
        $sql = new PohtoListModel();
        $info = $sql->with(['tanName', 'userInfo'])->find($id);
        if(empty($info)) {
            return $this->del($id);
        }
        $imgSql = new PohtoListImageModel();
        $imgwhereArr[] = ["photo_id", "=", $info['id']];
        $imgList = $imgSql
            ->where($imgwhereArr)
            ->order('sort desc')
            ->order('create_at asc')
            ->select()->toArray();
        $list = [];
        foreach ($imgList as $k => $v) {
            $ext = pathinfo($v['image_url'], PATHINFO_EXTENSION);
            if(empty($ext) || $ext == 'image') {
                $ext = 'jpg';
            }
            $oldPath = '/'.$info['institution_name'].'/'.$info['tabName'].'/'.$info['author_name'].'/'.$info['name'].'/';
            $path = $oldPath.($k+1).'.'.$ext;
            $list[] = [
                'id' => $v['id'],
                'image_path' => $path
            ];
        }
        $imgSql->saveAll($list);
         return result()->success(true);
    }

    public function downloadImage($url, $savePath) {
        if (file_exists($savePath)) {
            return;
        }
        try {
            $contextOptions = [
                "ssl" => [
                    "verify_peer" => false,
                    "verify_peer_name" => false,
                ],
            ];
            $context = stream_context_create($contextOptions);
            $imageData = file_get_contents($url, false, $context);
            $dirPath = dirname($savePath);
            if (!file_exists($dirPath)) {
                mkdir($dirPath, 0777, true);
            }
            file_put_contents($savePath, $imageData);
        } catch (\Exception $e) {
            echo $e->getMessage();
            echo "\n";
            echo $savePath;
            echo "\n";
            return;
        }

    }
    public function save()
    {
        $id = request()->get('id');
        if(empty($id)) {
            return result()->fail("请输入id", 500);
        }
        $sql = new PohtoListModel();
        $info = $sql->with(['tanName', 'userInfo'])->find($id);
        $imgSql = new PohtoListImageModel();
        $imgwhereArr[] = ["photo_id", "=", $info['id']];
        $imgList = $imgSql
            ->where($imgwhereArr)
            ->order('sort desc')
            ->order('create_at asc')
            ->select()->toArray();
        foreach ($imgList as $k => $v) {
            $ext = pathinfo($v['image_url'], PATHINFO_EXTENSION);
            if(empty($ext) || $ext == 'image') {
                $ext = 'jpg';
            }
            $oldPath = 'E:/album/'.$info['institution_name'].'/'.$info['tabName'].'/'.$info['author_name'].'/'.$info['name'].'/';
            $imgPath = iconv('UTF-8', 'GBK', $oldPath);
            if (!empty($imgPath)) {
                $dirPath = dirname($imgPath);
                if (!file_exists($dirPath)) {
                    mkdir($dirPath, 0777, true);
                }
            } else {
                return result()->fail('路径无效: ' . $imgPath, 500);
            }
            $path = $oldPath.($k+1).'.'.$ext;
            $this->downloadImage($v['image_url'], $path);
        }
        return result()->success("执行完成");
    }


    public function dingzhi()
    {
        $oldName = '75.Kitaro';
        $newName = '75Kitaro';
        $imgSql = new PohtoListImageTwo();
        $whereArr[] = ["image_path", "LIKE", '%'.$oldName.'%'];
        $imgList = $imgSql
            ->where($whereArr)
            ->limit(1)
            ->select()
            ->toArray();
        if(count($imgList) == 0) {
            return result()->fail("没有数据", 500);
        }
        $photoId = $imgList[0]['photo_id'];
        $imgList = $imgSql
            ->where('photo_id', '=', $photoId)
            ->select()
            ->toArray();
        foreach ($imgList as $k => $v) {
            $newPath = str_replace($oldName, $newName, $v['image_path']);
            $list[] = [
                'id' => $v['id'],
                'image_path' => $newPath,
            ];
        }
        Db::startTrans();
        try {
            $imgSql->saveAll($list);
            $sql = new PohtoListModel();
            $info = $sql->find($photoId);
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            return result()->fail($th->getMessage(), 500);
        }
        try {
            $url = 'http://localhost:7001/image/auth?photo_id='.$info->id;
            $response = file_get_contents($url);
            if ($response === FALSE) {
                return result()->fail('失败:'.$info->id, 500);

            } else {
                return result()->success(true);
            }
        } catch (\Throwable $th) {
            return result()->fail('失败:'.$info->id, 500);
        }
    }

    public function testDs()
    {
        $sql = new PohtoListModel();
        $list = $sql->where('name', 'like', '%.%')->limit(1)->select()->toArray();
        dump($list);
        if(count($list) == 0) {
            return result()->fail("没有数据", 500);
        }
        $info = $list[0];
        $info['name'] = str_replace('.', '', $info['name']);
        $imgSql = new PohtoListImageTwo();
        $imgList = $imgSql->where('photo_id', '=', $info['id'])->select()->toArray();
        $sql->update([
            'name' => $info['name']
        ], [
            'id' => $info['id']
        ]);
        $oldPath = '';
        foreach ($imgList as $k => $v) {
            $paths = explode('/', $v['image_path']);
            $last = $paths[count($paths) - 1];
            array_pop($paths);
            $qianPath = implode('/', $paths);
            if($k == 0) {
                $oldPath = 'E:/album'.implode('/', $paths);
            }

            $newPath = str_replace('.', '', $qianPath).'/'.$last;
            $arr[] = [
                'id' => $v['id'],
                'image_path' => $newPath,
            ];
        }
        dump($arr);
        $allPath = 'E:/album'.$arr[0]['image_path'];
        $paths = explode('/', $allPath);
        array_pop($paths);
        $newPath = implode('/', $paths);
        // 本地文件夹重命名
        if (!file_exists($newPath)) {
            rename($oldPath, $newPath);
        }
        $imgSql->saveAll($arr);
    }

    public function upoadMap()
    {
        $client = new Client([
            'verify' => false,
            'timeout' => 30, // 增加超时时间到30秒
        ]);
        try {
            $response = $client->post('https://catbox.moe/user/api.php', [
                'multipart' => [
                    [
                        'name' => 'reqtype',
                        'contents' => 'urlupload'
                    ],
                    [
                        'name' => 'userhash',
                        'contents' => '19b077fc9d4b5880445e55cc0'
                    ],
                    [
                        'name' => 'url',
                        'contents' => 'https://cdn.uviewui.com/uview/swiper/2.jpg'
                    ]
                ]
            ]);
            dump($response->getBody()->getContents());
        } catch (RequestException $e) {
            echo 'Error: ' . $e->getMessage();
            if ($e->hasResponse()) {
                echo 'Response: ' . $e->getResponse()->getBody()->getContents();
            }
        } catch (\Exception $e) {
            echo 'General Error: ' . $e->getMessage();
        }
    }
}
